<?php

class Auth extends Base {
	const AUTH_COOKIE_NAME = '_auth';
	const AUTH_COOKIE_PATH = '/';
	const AUTH_COOKIE_DOMAIN = HOSTNAME;
	const REGTYPE_MAIL = 0;
	const REGTYPE_MOBILE = 1;
	const AUTHTYPE_STATIC_PASSWD = 0;
	const AUTHTYPE_DYNAMIC_PASSWD = 1;
	const AUTHTYPE_NO_PASSWD = 2;
	const REMEMBERPASSWD_NOT = 0;
	const REMEMBERPASSWD_DO = 1;
	const REMEMBER_EXPIRETIME = 2592000;//半个月
	/**
	 * 服务器异常相关错误
	 */
	private static $_errorSrv = array(
		ERROR_MP_NO_RESP, 
		ERROR_MP_DEFAULT, 
		ERROR_MP_DATABASE_ERROR, 
		ERROR_CMIUP_DEFAULT,
		ERROR_CMIUP_NETWORK_ERROR,
		ERROR_CMIUP_DATABASE_ERROR,
		ERROR_SMS_DEFAULT
	);

	//{{{ userLogin($mobile, $password = '', $rememberPassword = self::REMEMBERPASSWD_NOT, $authType = self::AUTHTYPE_STATIC_PASSWD)
	/**
	 * userLogin
	 *
	 * 通过手机号和密码/动态密码登录
	 * 
	 * @param string	$mobile				手机号
	 * @param string	$password			密码	
	 * @param string	$rememberPassword	是否记住密码
	 * @param string	$authType			校验方式	
	 * @static
	 * @access public
	 * @return boolean
	 */
	public static function userLogin($mobile, $password = '', $rememberPassword = self::REMEMBERPASSWD_NOT, $authType = self::AUTHTYPE_STATIC_PASSWD) {
		self::clearError();
		$random = self::_createRandom();
		$loginIp = Utility::getRemoteIp();
		if (self::AUTHTYPE_NO_PASSWD !== $authType) {
//			$encryptedPassword = self::_encryptPassword($mobile, $password, $random);
			$encryptedPassword = md5( $password );
		}
		$result = MI_Cmiup::userLogin(self::REGTYPE_MOBILE, $mobile, $authType, $random, $encryptedPassword, $rememberPassword, null, $loginIp);
		$expireTime = $rememberPassword ? time() + self::REMEMBER_EXPIRETIME : 0;
		//出错处理
		if (false == $result) {
			//self::setError(Error::ERROR_CMIUP_DEFAULT);
			return false;
		}
		if (1 != $result['result']) {
			//self::setError(Error::getErrorByCmiupErrorNo($result['errorMessage']));
			return false;
		}
		$authToken = $result['authToken'];
		self::_setAuthToken($authToken, $expireTime);
		return $result['userId'];
	}//}}}

	//{{{ logout($userId)
	/**
	 * logout 
	 *
	 * 退出
	 * 
	 * @param string	$userId	 当前登录用户Id
	 * @static
	 * @access public
	 * @return boolean
	 */
	public static function logout($userId) {
		self::clearError();
		$result = MI_Cmiup::userLogout(null, $userId);
		if (false == $result) {
			self::setError(Error::ERROR_CMIUP_DEFAULT);
			return false;
		}
		if (0 != $result['status']) {
			self::setError(Error::getErrorByCmiupErrorNo($result['message']));
			return false;
		}
		$expireTime = time() - 7200;
		setcookie(self::AUTH_COOKIE_NAME, '', $expireTime, self::AUTH_COOKIE_PATH, self::AUTH_COOKIE_DOMAIN);
		return true;
	}//}}}

	//{{{ isLogined()
	/**
	 * isLogined 
	 *
	 * 判断当期是否处于登录状态
	 * 
	 * @static
	 * @access public
	 * @return int/false  登录状态返回登录用户Id, 否则返回false
	 */
	public static function isLogined() {
		self::clearError();
		if (!isset($_COOKIE[self::AUTH_COOKIE_NAME])) {
			//self::setError(ERROR_AUTH_NOTLOGINED);
			return false;
		}
		$info = encrypt_getlogininfo($_COOKIE[self::AUTH_COOKIE_NAME]);
		if (is_array($info) && isset($info['uid']) && 0 < $info['uid']) {
			return $info['uid'];
		}
		//self::setError(ERROR_AUTH_NOTLOGINED);
		return false;
	}//}}}

	//{{{ getMobileById($viewerId, $userId)
	/**
	 * getMobileById 
	 *
	 * 通过用户Id查询手机号
	 * 
	 * @param string	$viewerId	当前用户
	 * @param string	$userId		被查询用户Id	
	 * @static
	 * @access public
	 * @return int/boolean		成功返回手机号，失败返回false
	 */
	public static function getMobileById($viewerId, $userId) {
		$result = MI_Cmiup::getSimpleProfileByBatchUserId($viewerId, array($userId));
		//出错处理
		if (false == $result) {
			self::setError(Error::ERROR_CMIUP_DEFAULT);
			return false;
		}
		if (1 != $result['result']) {
			self::setError(Error::getErrorByCmiupErrorNo($result['errorMessage']));
			return false;
		}
		if (isset($result['simpleProfileList']) && $result['simpleProfileList'][0]['userId'] == $userId) {
			return $result['simpleProfileList'][0]['mobile'];
		}
		self::setError(ERROR_USER_NO_USER);
		return false;
	}//}}}

	//{{{ getUserIdByMobile($mobile)
	/**
	 * getUserIdByMobile 
	 *
	 * 通过手机号获取用户Id
	 * 
	 * @param string	$mobile		手机号
	 * @static
	 * @access public
	 * @return void
	 */
	public static function getUserIdByMobile($mobile) {
		$result = MI_Cmiup::hasProfileUser($mobile, self::REGTYPE_MOBILE);
		//出错处理
		if (false == $result) {
			self::setError(Error::ERROR_CMIUP_DEFAULT);
			return false;
		}
		if (1 != $result['result']) {
			self::setError(Error::getErrorByCmiupErrorNo($result['errorMessage']));
			return false;
		}
		return (0 >= $result['userId'] ? 0 : $result['userId']);
	}//}}}

	//{{{ sendSmsForChangePassword($mobile)
	/**
	 * sendSmsForChangePassword 
	 *
	 * 发送修改密码的验证码短信
	 * 
	 * @param string	$mobile		手机号
	 * @static
	 * @access public
	 * @return boolean
	 */
	public static function sendSmsForChangePassword($mobile) {
		self::clearError();
		$result = MI_Cmiup::sendAuthCodeForResetPwd($mobile);
		//出错处理
		if (false == $result) {
			//self::setError(Error::ERROR_CMIUP_DEFAULT);
			self::setError(Error::ERROR_SMS_SEND);
			return false;
		}
		if (1 != $result['result']) {
			$errorMsg = Error::getErrorByCmiupErrorNo($result['errorMessage']);
			if(in_array($errorMsg, self::$_errorSrv)){
				$errorMsg = ERROR_SMS_SEND;
			}
			self::setError($errorMsg);
			return false;
		}
		return true;
	}//}}}

	//{{{ changePassword($mobile = null, $userId = null, $smsCode, $password)
	/**
	 * changePassword 
	 *
	 * 修改密码
	 * 
	 * @param string	$mobile		手机号
	 * @param string	$userId		用户id, 以上两项至少一个不能为空
	 * @param string	$smsCode	短信验证码	
	 * @param string	$password	新密码
	 * @static
	 * @access public
	 * @return void
	 */
	public static function changePassword($mobile = null, $userId = null, $smsCode, $password) {
		self::clearError();
		$encryptedPassword = self::_createPassword($password);
		$result = MI_Cmiup::resetUserPassword($mobile, $userId, $smsCode, $encryptedPassword);
		//出错处理
		if (false == $result) {
			self::setError(Error::ERROR_CMIUP_DEFAULT);
			return false;
		}
		if (1 != $result['result']) {
			self::setError(Error::getErrorByCmiupErrorNo($result['errorMessage']));
			return false;
		}
		return true;
	}//}}}

	//{{{ sendDynamicPassword($mobile)
	/**
	 * sendDynamicPassword 
	 *
	 * 下发动态密码
	 *
	 * @param string	$mobile	
	 * @static
	 * @access public
	 * @return boolean
	 */
	public static function sendDynamicPassword($mobile) {
		$result = MI_Cmiup::userDynamicPasswordSend(self::REGTYPE_MOBILE, $mobile);
		//出错处理
		if (false == $result) {
			//self::setError(Error::ERROR_CMIUP_DEFAULT);
			self::setError(Error::ERROR_SMS_SEND);
			return false;
		}
		if (1 != $result['result']) {
			$errorMsg = Error::getErrorByCmiupErrorNo($result['errorMessage']);
			if(in_array($errorMsg, self::$_errorSrv)){
				$errorMsg = ERROR_SMS_SEND;
			}
			self::setError($errorMsg);
			return false;
		}
		return true;
	}//}}}

	//{{{ sendSmsForRegister($mobile)
	/**
	 * sendSmsForRegister 
	 * 
	 * 下行注册短信验证码
	 *
	 * @param string	$mobile	
	 * @static
	 * @access public
	 * @return boolean
	 */
	public static function sendSmsForRegister($mobile) {
		$result = MI_Cmiup::userAuthCodeSend($mobile);
		//出错处理
		if (false == $result) {
			self::setError(Error::ERROR_CMIUP_DEFAULT);
			return false;
		}
		if (1 != $result['result']) {
			self::setError(Error::getErrorByCmiupErrorNo($result['errorMessage']));
			return false;
		}
		return true;
	}//}}}

	//{{{ activateUserByMobile($mobile, $smsCode, $password, $ip, $inviteUserId=null, $channel=null)
	/**
	 * activateUserByMobile 
	 *
	 * 通过短信验证码激活社区账号
	 * 
	 * @param string	$mobile			必填	手机号
	 * @param string	$smsCode		必填	短信验证码	
	 * @param string	$password		必填	密码	
	 * @param string	$ip				注册Ip
	 * @param string	$inviteUserId	邀请者Id
	 * @static
	 * @access public
	 * @return int/boolean	成功返回用户Id, 失败返回false
	 */
	public static function activateUserByMobile($mobile, $smsCode, $password, $ip, $inviteUserId=null, $channel=null) {
		//check smscode
		$result = MI_Cmiup::checkAuthCode($mobile, $smsCode);
		//出错处理
		if (false == $result) {
			self::setError(Error::ERROR_CMIUP_DEFAULT);
			return false;
		}
		if (1 != $result['result']) {
			self::setError(Error::getErrorByCmiupErrorNo($result['errorMessage']));
			return false;
		}

		//check password
		if (!self::checkPassword($password)) {
			return false;
		}

		//active
		$encryptedPassword = self::_createPassword($password);
		$result = MI_Cmiup::registerUser(self::REGTYPE_MOBILE, $mobile, $encryptedPassword, null, null, null, $ip, null);
		//出错处理
		if (false == $result) {
			self::setError(Error::ERROR_CMIUP_DEFAULT);
			return false;
		}
		if (1 != $result['result']) {
			self::setError(Error::getErrorByCmiupErrorNo($result['errorMessage']));
			return false;
		}
		return $result['userId'];
	}//}}}

	//{{{ checkPassword($password)
	/**
	 * checkPassword 
	 *
	 * 验证密码强度
	 * 
	 * @param string	$password	
	 * @static
	 * @access public
	 * @return boolean
	 */
	public static function checkPassword($password) {
		$encryptedPassword = self::_createPassword($password);
		$result = MI_Cmiup::validatePassword($encryptedPassword);
		//出错处理
		if (false == $result) {
			self::setError(Error::ERROR_CMIUP_DEFAULT);
			return false;
		}
		if (1 != $result['result']) {
			self::setError(Error::getErrorByCmiupErrorNo($result['errorMessage']));
			return false;
		}
		return true;
	}//}}}
	
	//{{{ getUserState($userId)
	/**
	 * getUserState 
	 *
	 * 用户帐号状态
	 * 
	 * @param string	$userId		被查询用户Id	
	 * @static
	 * @access public
	 * @return boolean
	 */
	public static function getUserState($userId) {		
		$result = MI_Cmiup::findProfileUser($userId, $userId);
		//出错处理
		if (false == $result) {
			self::setError(Error::ERROR_CMIUP_DEFAULT);
			return false;
		}
		if (1 != $result['result']) {
			self::setError(Error::getErrorByCmiupErrorNo($result['errorMessage']));
			return false;
		}
		if (isset($result['user']['userId']) && $result['user']['userId'] == $userId) {
			if (isset($result['user']['userState']) && $result['user']['userState'] == 1) {
				return true;
			} else {
				return false;
			}
		}
		self::setError(ERROR_USER_NO_USER);
		return false;		
	}//}}}	

	//{{{ private functions
	private static function _createRandom() {
		return mt_rand();
	}

	private static function _createPassword($password) {
		return md5($password);
	}

	private static function _encryptPassword($account, $password, $random) {
//		return strtoupper(md5($account. strtoupper(self::_createPassword($password)) . $random));
		return md5($account);
	}

	private static function _setAuthToken($authToken, $expireTime) {
		setcookie(self::AUTH_COOKIE_NAME, $authToken, $expireTime, self::AUTH_COOKIE_PATH, self::AUTH_COOKIE_DOMAIN);
	}
	//}}}
}
